// 游戏化学习工具函数

// 等级配置
export interface LevelConfig {
  level: number
  name: string
  expRequired: number
  rewards: {
    points: number
    title?: string
    badge?: string
  }
}

// 任务类型
export interface Task {
  id: number
  title: string
  description: string
  type: 'daily' | 'weekly' | 'achievement'
  icon: string
  progress: number
  target: number
  reward: number
  completed: boolean
  claimed: boolean
  expiresAt?: Date
}

// 成就类型
export interface Achievement {
  id: number
  title: string
  description: string
  icon: string
  category: 'learning' | 'social' | 'streak' | 'special'
  progress: number
  target: number
  reward: number
  unlocked: boolean
  unlockedAt?: Date
}

// 等级配置表
export const LEVEL_CONFIGS: LevelConfig[] = [
  { level: 1, name: '新手', expRequired: 0, rewards: { points: 0 } },
  { level: 2, name: '初学者', expRequired: 100, rewards: { points: 50 } },
  { level: 3, name: '入门者', expRequired: 300, rewards: { points: 100 } },
  { level: 4, name: '学习者', expRequired: 600, rewards: { points: 150 } },
  { level: 5, name: '探索者', expRequired: 1000, rewards: { points: 200, title: '探索者' } },
  { level: 6, name: '实践者', expRequired: 1500, rewards: { points: 250 } },
  { level: 7, name: '熟练者', expRequired: 2100, rewards: { points: 300 } },
  { level: 8, name: '进阶者', expRequired: 2800, rewards: { points: 350 } },
  { level: 9, name: '专家', expRequired: 3600, rewards: { points: 400, title: '专家' } },
  {
    level: 10,
    name: '大师',
    expRequired: 4500,
    rewards: { points: 500, title: '大师', badge: 'gold' },
  },
  { level: 11, name: '宗师', expRequired: 5500, rewards: { points: 600, title: '宗师' } },
  { level: 12, name: '传奇', expRequired: 6600, rewards: { points: 700, title: '传奇' } },
  { level: 13, name: '神话', expRequired: 7800, rewards: { points: 800, title: '神话' } },
  { level: 14, name: '传说', expRequired: 9100, rewards: { points: 900, title: '传说' } },
  {
    level: 15,
    name: '至尊',
    expRequired: 10500,
    rewards: { points: 1000, title: '至尊', badge: 'diamond' },
  },
]

// 获取用户等级信息
export function getUserLevel(exp: number): {
  level: number
  name: string
  progress: number
  nextLevelExp: number
} {
  let currentLevel = 1
  let currentLevelConfig = LEVEL_CONFIGS[0]

  for (let i = LEVEL_CONFIGS.length - 1; i >= 0; i--) {
    if (exp >= LEVEL_CONFIGS[i].expRequired) {
      currentLevel = LEVEL_CONFIGS[i].level
      currentLevelConfig = LEVEL_CONFIGS[i]
      break
    }
  }

  const nextLevelConfig = LEVEL_CONFIGS.find((config) => config.level === currentLevel + 1)
  const nextLevelExp = nextLevelConfig
    ? nextLevelConfig.expRequired
    : currentLevelConfig.expRequired
  const progress = nextLevelConfig
    ? ((exp - currentLevelConfig.expRequired) /
        (nextLevelConfig.expRequired - currentLevelConfig.expRequired)) *
      100
    : 100

  return {
    level: currentLevel,
    name: currentLevelConfig.name,
    progress: Math.min(progress, 100),
    nextLevelExp,
  }
}

// 计算经验值奖励
export function calculateExpReward(
  action: string,
  difficulty: 'easy' | 'medium' | 'hard' = 'medium',
): number {
  const baseRewards: Record<string, number> = {
    complete_course: 100,
    complete_lesson: 20,
    submit_assignment: 50,
    take_exam: 80,
    participate_discussion: 10,
    daily_checkin: 30,
    weekly_goal: 200,
    achievement_unlock: 150,
  }

  const difficultyMultipliers = {
    easy: 0.8,
    medium: 1.0,
    hard: 1.5,
  }

  const baseReward = baseRewards[action] || 10
  return Math.round(baseReward * difficultyMultipliers[difficulty])
}

// 检查是否升级
export function checkLevelUp(oldExp: number, newExp: number): LevelConfig | null {
  const oldLevel = getUserLevel(oldExp).level
  const newLevel = getUserLevel(newExp).level

  if (newLevel > oldLevel) {
    return LEVEL_CONFIGS.find((config) => config.level === newLevel) || null
  }

  return null
}

// 生成每日任务
export function generateDailyTasks(): Task[] {
  const tasks: Task[] = [
    {
      id: 1,
      title: '完成一节课程',
      description: '观看并完成任意一节课程的学习',
      type: 'daily',
      icon: 'play-circle',
      progress: 0,
      target: 1,
      reward: 50,
      completed: false,
      claimed: false,
      expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24小时后过期
    },
    {
      id: 2,
      title: '提交一份作业',
      description: '完成并提交一份课程作业',
      type: 'daily',
      icon: 'file-text',
      progress: 0,
      target: 1,
      reward: 100,
      completed: false,
      claimed: false,
      expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
    },
    {
      id: 3,
      title: '参与讨论',
      description: '在课程讨论区发表评论',
      type: 'daily',
      icon: 'message',
      progress: 0,
      target: 3,
      reward: 30,
      completed: false,
      claimed: false,
      expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
    },
    {
      id: 4,
      title: '学习打卡',
      description: '连续学习打卡',
      type: 'daily',
      icon: 'calendar',
      progress: 0,
      target: 1,
      reward: 20,
      completed: false,
      claimed: false,
      expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
    },
  ]

  return tasks
}

// 生成每周任务
export function generateWeeklyTasks(): Task[] {
  const tasks: Task[] = [
    {
      id: 5,
      title: '完成5门课程',
      description: '在一周内完成5门不同的课程',
      type: 'weekly',
      icon: 'book',
      progress: 0,
      target: 5,
      reward: 500,
      completed: false,
      claimed: false,
      expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7天后过期
    },
    {
      id: 6,
      title: '获得3个成就',
      description: '解锁3个新的成就',
      type: 'weekly',
      icon: 'trophy',
      progress: 0,
      target: 3,
      reward: 300,
      completed: false,
      claimed: false,
      expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
    },
    {
      id: 7,
      title: '连续学习7天',
      description: '连续7天进行学习',
      type: 'weekly',
      icon: 'fire',
      progress: 0,
      target: 7,
      reward: 400,
      completed: false,
      claimed: false,
      expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
    },
  ]

  return tasks
}

// 预定义成就列表
export function getPredefinedAchievements(): Achievement[] {
  return [
    {
      id: 1,
      title: '初出茅庐',
      description: '完成第一门课程',
      category: 'learning',
      icon: 'star',
      progress: 0,
      target: 1,
      reward: 100,
      unlocked: false,
    },
    {
      id: 2,
      title: '学习达人',
      description: '完成10门课程',
      category: 'learning',
      icon: 'crown',
      progress: 0,
      target: 10,
      reward: 500,
      unlocked: false,
    },
    {
      id: 3,
      title: '坚持不懈',
      description: '连续学习30天',
      category: 'streak',
      icon: 'fire',
      progress: 0,
      target: 30,
      reward: 1000,
      unlocked: false,
    },
    {
      id: 4,
      title: '社交达人',
      description: '发表100条评论',
      category: 'social',
      icon: 'team',
      progress: 0,
      target: 100,
      reward: 300,
      unlocked: false,
    },
    {
      id: 5,
      title: '考试高手',
      description: '获得10次考试满分',
      category: 'learning',
      icon: 'trophy',
      progress: 0,
      target: 10,
      reward: 800,
      unlocked: false,
    },
    {
      id: 6,
      title: '知识渊博',
      description: '学习100小时',
      category: 'learning',
      icon: 'book',
      progress: 0,
      target: 100,
      reward: 600,
      unlocked: false,
    },
    {
      id: 7,
      title: '助人为乐',
      description: '帮助其他学员解答问题50次',
      category: 'social',
      icon: 'heart',
      progress: 0,
      target: 50,
      reward: 400,
      unlocked: false,
    },
    {
      id: 8,
      title: '完美主义者',
      description: '所有作业都获得优秀评价',
      category: 'learning',
      icon: 'check-circle',
      progress: 0,
      target: 20,
      reward: 700,
      unlocked: false,
    },
  ]
}

// 检查成就进度
export function checkAchievementProgress(
  achievements: Achievement[],
  userStats: {
    completedCourses: number
    studyStreak: number
    comments: number
    perfectExams: number
    studyHours: number
    helpCount: number
    excellentAssignments: number
  },
): Achievement[] {
  return achievements.map((achievement) => {
    let progress = 0

    switch (achievement.id) {
      case 1: // 初出茅庐
        progress = Math.min(userStats.completedCourses, 1)
        break
      case 2: // 学习达人
        progress = Math.min(userStats.completedCourses, 10)
        break
      case 3: // 坚持不懈
        progress = Math.min(userStats.studyStreak, 30)
        break
      case 4: // 社交达人
        progress = Math.min(userStats.comments, 100)
        break
      case 5: // 考试高手
        progress = Math.min(userStats.perfectExams, 10)
        break
      case 6: // 知识渊博
        progress = Math.min(userStats.studyHours, 100)
        break
      case 7: // 助人为乐
        progress = Math.min(userStats.helpCount, 50)
        break
      case 8: // 完美主义者
        progress = Math.min(userStats.excellentAssignments, 20)
        break
    }

    const wasUnlocked = achievement.unlocked
    const isNowUnlocked = progress >= achievement.target

    return {
      ...achievement,
      progress,
      unlocked: isNowUnlocked,
      unlockedAt: !wasUnlocked && isNowUnlocked ? new Date() : achievement.unlockedAt,
    }
  })
}

// 计算连续学习天数
export function calculateStudyStreak(checkinDates: Date[]): number {
  if (checkinDates.length === 0) return 0

  const sortedDates = checkinDates
    .map((date) => new Date(date))
    .sort((a, b) => b.getTime() - a.getTime()) // 降序排列

  let streak = 0
  const today = new Date()
  today.setHours(0, 0, 0, 0)

  let currentDate = today

  for (const checkinDate of sortedDates) {
    const checkinDay = new Date(checkinDate)
    checkinDay.setHours(0, 0, 0, 0)

    const diffTime = currentDate.getTime() - checkinDay.getTime()
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

    if (diffDays <= 1) {
      streak++
      currentDate = checkinDay
    } else {
      break
    }
  }

  return streak
}

// 格式化数字显示
export function formatNumber(num: number): string {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K'
  }
  return num.toString()
}

// 获取随机鼓励语
export function getRandomEncouragement(): string {
  const encouragements = [
    '学习如逆水行舟，不进则退！',
    '今天的努力，是明天的收获！',
    '知识改变命运，学习成就未来！',
    '坚持就是胜利，加油！',
    '每一次学习都是成长的机会！',
    '你的努力，终将绽放光芒！',
    '学习路上，你并不孤单！',
    '相信自己，你可以做到！',
    '知识就是力量，继续前进！',
    '今天的付出，明天的回报！',
  ]

  return encouragements[Math.floor(Math.random() * encouragements.length)]
}
